#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
#include <QPainter>
#include <QStyleOption>
#include <math.h>
#include "edge.h"
#include "node.h"
#include "semaphore.h"
#include "agent.h"
#include "graphwidget.h"

using namespace Traffic_Sim;

 Node::Node(GraphWidget *graphWidget, Traffic_Sim::Traffic_Node_Info & info) : graph(graphWidget), info(info)
 {
  setFlag(ItemIsMovable);
  setZValue(100);
  setPos(info.x,info.y);

 }

 void Node::addEdge(Edge *edge)
 {
     edgeList << edge;
     edge->adjust();
 }

 QList<Edge *> Node::edges() const
 {
     return edgeList;
 }


bool Node::advance()
{
     if (newPos == pos())
         return false;

     setPos(newPos);
     return true;
 }

 QRectF Node::boundingRect() const
 {
     qreal adjust = 2;
     return QRectF(-10 - adjust, -10 - adjust,
                   23 + adjust, 23 + adjust);
 }

 QPainterPath Node::shape() const
 {
     QPainterPath path;
     path.addEllipse(-10, -10, 20, 20);
     return path;
 }


 void Node::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *)
 {

 	update();
        painter->setPen(QPen(Qt::black, 0));
	painter->drawEllipse(-10, -10, 30, 30);
	painter->setPen(QPen(Qt::black, 0));
 }



 QVariant Node::itemChange(GraphicsItemChange change, const QVariant &value)
 {
     switch (change) {
     case ItemPositionChange:
         foreach (Edge *edge, edgeList)
             edge->adjust();
         break;
     default:
         break;
     };

     return QGraphicsItem::itemChange(change, value);
 }

 void Node::mousePressEvent(QGraphicsSceneMouseEvent *event)
 {
     update();
     QGraphicsItem::mousePressEvent(event);
 }

 void Node::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
 {
     update();
     QGraphicsItem::mouseReleaseEvent(event);
 }

Agent * Node::addAgent(Traffic_Vehicle * vehicle){
Agent * ag = new Agent(this);
ag->setAgent(vehicle);
graph->scene->addItem(ag);
update();
return ag;
}



Semaphore * Node::addSemaphore(Traffic_Semaphore * semaph){
Semaphore * sem = new Semaphore(this);
sem->setSemaphore(semaph);
graph->scene->addItem(sem);
update();
return sem;
}


